"use client"

import { useState, useEffect, useRef } from "react"
import "./ProfilePage.css"

function ProfilePage() {
  const [uploadingAvatar, setUploadingAvatar] = useState(false)
  const fileInputRef = useRef(null)

  const [activeTab, setActiveTab] = useState("downloads")
  const [torrents, setTorrents] = useState([])
  const [downloads, setDownloads] = useState([])
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState(null)
  const [isEditModalOpen, setIsEditModalOpen] = useState(false)
  const [inviteCode, setInviteCode] = useState("")
  const [copySuccess, setCopySuccess] = useState(false)

  // 主页面显示的用户信息
  const [userProfile, setUserProfile] = useState({
    avatarUrl: "/default_avatar.jpg",
    nickname: "",
    gender: "",
    bio: "介绍一下自己吧...",
    level: "",
    userPoints: "",
    shareRate: "",
    downloadCount: "",
  })

  // Modal中编辑的表单数据
  const [editForm, setEditForm] = useState({
    nickname: "",
    gender: "",
    bio: "介绍一下自己吧...",
    level: "",
    userPoints: "",
    shareRate: "",
    uploadCount: "",
    downloadCount: "",
  })

  const [assessmentStatus, setAssessmentStatus] = useState("未考核")
  const [totalCount, setTotalCount] = useState(0)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(5)
  const [perPage] = useState(10)

  const getAuthHeaders = () => {
    const token = localStorage.getItem("token")
    const userId = localStorage.getItem("userId")

    if (!token || !userId) {
      console.error("用户未登录")
      return null
    }

    return {
      Authorization: `Bearer ${token}`,
    }
  }

  // 获取用户头像
  const fetchUserAvatar = async () => {
    let avatarUrl = "/default_avatar.jpg";
    
    try {
      const userId = localStorage.getItem("userId");
      if (!userId) throw new Error("用户ID不存在");

      const response = await fetch(`/user/get-avatar?userId=${userId}`, {
        method: "GET",
        headers: getAuthHeaders(),
      });

      if (!response.ok) throw new Error(`获取头像失败: ${response.status}`);

      const data = await response.json();
      
      if (data.code === 0 && data.result) {
        avatarUrl = data.msg;

        if (avatarUrl) {
          if (avatarUrl.startsWith("data:image/")) {
            // Base64 with prefix
          } else if (avatarUrl.length > 1000) {
            avatarUrl = `data:image/jpeg;base64,${avatarUrl}`;
          } else if (!avatarUrl.startsWith("/") && !avatarUrl.startsWith("http")) {
            avatarUrl = `/${avatarUrl}`;
          }
        }
      }
    } catch (error) {
      console.error("获取头像错误:", error);
    }

    localStorage.setItem("avatarUrl", avatarUrl);
    return avatarUrl;
  };

  // 自动调整sizeGB
  const formatSize = (sizeInGB) => {
    const sizeInMB = sizeInGB * 1024
    const sizeInKB = sizeInMB * 1024

    if (sizeInGB >= 1) {
      // 大于等于1GB，显示GB并保留2位小数
      return `${sizeInGB.toFixed(2)} GB`
    } else if (sizeInMB >= 1) {
      // 大于等于1MB但小于1GB，显示MB并保留2位小数
      return `${sizeInMB.toFixed(2)} MB`
    } else {
      // 小于1MB，显示KB并取整数
      return `${sizeInKB.toFixed(2)} KB`
    }
  }

  const getSafeImageUrl = () => {
    return "/default_avatar.jpg"
  }

  // 处理头像上传
  const handleUpdateAvatar = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click()
    }
  }

  // 处理文件选择
  const handleAvatarFileChange = async (e) => {
    const file = e.target.files[0]
    if (!file) return

    // 验证文件类型
    const validTypes = ["image/jpeg", "image/jpg", "image/png", "image/webp", "image/gif"]
    if (!validTypes.includes(file.type)) {
      alert("请选择有效的图片格式 (JPG, PNG, WebP, GIF)")
      return
    }

    // 验证文件大小 (5MB)
    const maxSize = 5 * 1024 * 1024
    if (file.size > maxSize) {
      alert("图片文件大小不能超过5MB")
      return
    }

    setUploadingAvatar(true)

    try {
      const formData = new FormData()
      formData.append("userId", localStorage.getItem("userId"))
      formData.append("avatar", file)

      const response = await fetch("/user/upload-avatar", {
        method: "POST",
        headers: getAuthHeaders(),
        body: formData,
      })

      if (!response.ok) {
        throw new Error(`上传失败: ${response.status}`)
      }

      const data = await response.json()
      console.log("头像上传响应:", data)

      if (data.code === 0 && data.result) {
        // 重新获取头像和用户信息
        await fetchUserAvatar()
        fetchUserProfile()
        window.location.reload();
      } else {
        throw new Error(data.msg || "头像上传失败")
      }
    } catch (error) {
      console.error("头像上传错误:", error)
      alert(error.message || "头像上传失败，请重试")
    } finally {
      setUploadingAvatar(false)
      // 清空文件输入框
      if (fileInputRef.current) {
        fileInputRef.current.value = ""
      }
    }
  }

  // 获取用户信息
  const fetchUserProfile = async () => {
    try {
      const response = await fetch(`/user/level?userId=${localStorage.getItem("userId")}`, {
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取个人信息失败")
      }

      const data = await response.json()
      if (data.code === 0 && data.result) {
        const profileData = {
          userId: localStorage.getItem("userId"),
          nickname: data.rows.userData.nickname,
          gender: data.rows.userData.sex,
          bio: data.rows.userData.introduction,
          level: data.rows.userData.level,
          userPoints: data.rows.userData.userPoints,
          shareRate: data.rows.userData.shareRate,
          uploadCount: data.rows.userData.uploadCount,
          downloadCount: data.rows.userData.downloadCount,
        }

        // 更新主页面显示的用户信息（保持原有头像URL）
        setUserProfile((prev) => ({
          ...prev,
          ...profileData,
        }))

        // 同时更新编辑表单的初始数据
        setEditForm(profileData)
      } else {
        throw new Error(data.msg || "获取个人信息失败")
      }
    } catch (err) {
      console.error("获取个人信息错误:", err)
    }
  }

  // 打开编辑模态框时，重置编辑表单为当前用户信息
  const handleOpenEditModal = () => {
    setEditForm({
      ...userProfile,
    })
    setIsEditModalOpen(true)
  }

  // 获取用户上传的种子列表
  const fetchUserTorrents = async () => {
    if (activeTab !== "uploads") return

    setIsLoading(true)
    setError(null)

    try {
      const response = await fetch(`/torrent/getUserTorrents?user_id=${localStorage.getItem("userId")}`, {
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取种子列表失败")
      }

      const data = await response.json()
      console.log("获取种子列表:", data)

      if (data.code === 0 && data.result) {
        setTorrents(data.rows || [])
      } else {
        throw new Error(data.msg || "获取种子列表失败")
      }
    } catch (err) {
      setError(err.message)
      console.error("获取种子列表错误:", err)
    } finally {
      setIsLoading(false)
    }
  }

  // 获取用户下载记录
  const fetchDownloadRecords = async (page = currentPage) => {
    if (activeTab !== "downloads") return

    setIsLoading(true)
    setError(null)

    try {
      const response = await fetch(
        `/download/records?user_id=${localStorage.getItem("userId")}&page=${page}&per_page=${perPage}`,
        {
          headers: getAuthHeaders(),
        },
      )

      if (!response.ok) {
        throw new Error("获取下载列表失败")
      }

      const data = await response.json()
      console.log("获取下载列表:", data)

      if (data.code === 0 && data.result) {
        setDownloads(data.rows || [])
        setTotalCount(data.total || 0)
        if (data.total) {
          setTotalPages(Math.ceil(data.total / perPage))
        }
      } else {
        throw new Error(data.msg || "获取下载列表失败")
      }
    } catch (err) {
      setError(err.message)
      console.error("获取下载列表错误:", err)
    } finally {
      setIsLoading(false)
    }
  }

  // 获取邀请码
  const fetchInviteCode = async () => {
    try {
      const response = await fetch(`/invitecode/generatecode?user_id=${localStorage.getItem("userId")}`, {
        method: "POST",
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取邀请码失败")
      }

      const data = await response.json()
      if (data.code === 0 && data.result && data.rows?.code) {
        setInviteCode(data.rows.code)
      } else {
        setInviteCode("已达本月生成上限")
      }
    } catch (err) {
      console.error("获取邀请码错误:", err)
      setInviteCode("获取失败")
    }
  }

  // 删除上传记录
  const handleDeleteUploadRecord = async (torrentId) => {
    if (window.confirm('确定要删除这条种子吗？')) {
      try {
        const response = await fetch(`/torrent/deleteTorrent?user_id=${localStorage.getItem('userId')}&torrent_id=${torrentId}`, {
          method: 'DELETE',
          headers: getAuthHeaders()
        });
        
        if (!response.ok) {
          throw new Error("网络请求失败");
        }

        const data = await response.json();
        if (data.code === 0 && data.result) {
          fetchUserTorrents(); // 删除成功，刷新列表
        } else {
          throw new Error(data.msg || "服务器返回错误");
        }
      } catch (err) {
        console.error("删除种子失败:", err);
        window.alert(`删除失败: ${err.message}`); // 弹出错误提示
      }
    }
  };
  

  // 获取考核结果
  const fetchAssessmentStatus = async () => {
    try {
      const response = await fetch(`/user/assessment/latestResult?userId=${localStorage.getItem("userId")}`, {
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("获取考核结果失败")
      }

      const data = await response.json()
      console.log("考核结果", data)
      if (data.code === 0 && data.rows) {
        setAssessmentStatus(data.rows.assessmentStatus)
      } else {
        throw new Error(data.msg || "获取考核结果失败")
      }
    } catch (err) {
      console.error("获取考核结果错误:", err)
    }
  }

  useEffect(() => {
    fetchAssessmentStatus()
    fetchUserProfile()
    fetchUserAvatar()
  }, [])

  useEffect(() => {
    if (activeTab === "uploads") {
      fetchUserTorrents()
    } else if (activeTab === "downloads") {
      fetchDownloadRecords(1)
      setCurrentPage(1)
    }
  }, [activeTab])

  const handlePageChange = (page) => {
    setCurrentPage(page)
    fetchDownloadRecords(page)
  }

  const renderPagination = () => {
    const pages = []

    const startPage = Math.max(1, currentPage - 2)
    const endPage = Math.min(totalPages, currentPage + 2)

    if (startPage > 1) {
      pages.push(
        <button key="first" className="page-button" onClick={() => handlePageChange(1)}>
          首页
        </button>,
      )
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        <button
          key={i}
          className={`page-button ${i === currentPage ? "active" : ""}`}
          onClick={() => handlePageChange(i)}
        >
          {i}
        </button>,
      )
    }

    if (endPage < totalPages) {
      pages.push(
        <button key="last" className="page-button" onClick={() => handlePageChange(totalPages)}>
          末页
        </button>,
      )
    }

    return pages
  }

  const handleDeleteDownloadRecord = async (downloadId, userId) => {
    if (window.confirm("确定要删除这条下载记录吗？")) {
      const response = await fetch(
        `/download/deleteRecord?download_id=${downloadId}&user_id=${localStorage.getItem("userId")}`,
        {
          method: "DELETE",
          headers: getAuthHeaders(),
        },
      )
      console.log("删除下载记录:", response)

      fetchDownloadRecords(1)
    }
  }

  const handleEditSubmit = async (e) => {
    e.preventDefault()
    setIsLoading(true)
    setError(null)

    try {
      // 构建请求体 - 使用相对路径
      const requestBody = {
        userId: Number.parseInt(localStorage.getItem("userId")),
        nickname: editForm.nickname,
        sex: editForm.gender === "male" ? "男" : editForm.gender === "female" ? "女" : editForm.gender,
        introduction: editForm.bio,
      }

      console.log("提交用户更新请求:", requestBody)

      const response = await fetch("/user/update", {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestBody),
      })

      if (!response.ok) {
        const errorText = await response.text()
        console.error("服务器响应错误:", response.status, errorText)
        throw new Error(`更新失败 (${response.status}): ${errorText}`)
      }

      const data = await response.json()
      console.log("服务器响应:", data)

      if (data.code === 0 && data.result) {
        alert("个人资料更新成功！")

        // 更新主页面显示的用户信息
        setUserProfile({
          ...userProfile,
          nickname: editForm.nickname,
          gender: editForm.gender,
          bio: editForm.bio,
        })

        // 关闭模态框
        setIsEditModalOpen(false)

        // 重新获取最新的用户信息
        fetchUserProfile()
      } else {
        throw new Error(data.msg || "更新个人资料失败")
      }
    } catch (err) {
      console.error("更新个人资料错误:", err)
      // 提供更详细的错误信息
      let errorMessage = "更新个人资料失败，请稍后重试"
      if (err.message.includes("400")) {
        errorMessage = "请求格式错误，请检查输入信息"
      } else if (err.message.includes("401")) {
        errorMessage = "登录已过期，请重新登录"
      } else if (err.message.includes("500")) {
        errorMessage = "服务器内部错误，请稍后重试"
      } else if (err.message) {
        errorMessage = err.message
      }

      alert(errorMessage)
    } finally {
      setIsLoading(false)
    }
  }

  // 封号用户
  const handleBatchBanUsers = async (e) => {
    if (!window.confirm("确定封禁所有违规用户吗？")) return;
    
    try {
      const response = await fetch('/admin/batchBanUsers', {
        method: "POST",
        headers: getAuthHeaders()
      });

      if (!response.ok) {
        throw new Error(`网络响应错误: ${response.status}`);
      }

      const result = await response.json();
      
      if (result.code === 0 && result.result) {
        alert(result.msg || "操作成功！");  // 使用服务端返回的成功消息
        // 这里可以添加成功后刷新数据等操作
      } else {
        const errorMsg = result.msg || result.message || "操作失败，请重试";
        alert(`错误: ${errorMsg}`);
      }
    } catch (error) {
      console.error("批量封禁失败:", error);
      alert(`操作失败: ${error.message || "网络请求异常"}`);
    }
  };

  const handleModalClose = () => {
    // 重置编辑表单为原始用户信息
    setEditForm({
      ...userProfile,
    })

    setIsEditModalOpen(false)
  }

  const handleRefreshInviteCode = async () => {
    fetchInviteCode()
  }

  const handleCopyInviteCode = () => {
    navigator.clipboard
      .writeText(inviteCode)
      .then(() => {
        setCopySuccess(true)
        setTimeout(() => setCopySuccess(false), 2000)
      })
      .catch((err) => {
        console.error("复制失败:", err)
      })
  }

  return (
    <div className="profile-page">
      <div className="profile-container">
        <div className="profile-grid">
          <div className="profile-sidebar">
            <div className="user-profile">
              <div className="user-avatar-container" onClick={handleUpdateAvatar}>
                <img
                  src={localStorage.getItem("avatarUrl") || "/default_avatar.jpg"}
                  alt="用户头像"
                  className="user-avatar"
                  onError={(e) => {
                    console.log("头像加载失败，使用默认头像")
                    e.target.src = "/default_avatar.jpg"
                  }}
                  onLoad={() => {
                    console.log("头像加载成功")
                  }}
                />
                {uploadingAvatar && (
                  <div className="avatar-uploading-overlay">
                    <div className="uploading-spinner"></div>
                    <span>上传中...</span>
                  </div>
                )}
                <div className="avatar-edit-badge">
                  <span>点击更换</span>
                </div>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/jpeg,image/jpg,image/png,image/webp,image/gif"
                  onChange={handleAvatarFileChange}
                  style={{ display: "none" }}
                />
              </div>
              <h2 className="user-name">{userProfile.nickname}</h2>
              <p className="user-gender">
                {userProfile.gender === "male" ? "男" : userProfile.gender === "female" ? "女" : userProfile.gender}
              </p>
              <p className="user-bio">{userProfile.bio}</p>

              <div className="user-stats">
                <div className="stat-item">
                  <span className="stat-label">积分:</span>
                  <span className="stat-value">{userProfile.userPoints}</span>
                </div>
                <div className="stat-item">
                  <span className="stat-label">上传/下载量:</span>
                  <span className="stat-value">
                    {userProfile.uploadCount}GB/{userProfile.downloadCount}GB
                  </span>
                </div>
                <div className="stat-item">
                  <span className="stat-label">分享率:</span>
                  <span className="stat-value">{Number(userProfile.shareRate).toFixed(2)}</span>
                </div>
                <div className="stat-item">
                  <span className="stat-label">等级:</span>
                  <span className="stat-value">{userProfile.level}级</span>
                </div>
                <div className="stat-item">
                  <span className="stat-label">考核:</span>
                  <span className="stat-value">{assessmentStatus}</span>
                </div>
                <div className="stat-item invite-code-item">
                  <span className="stat-label">邀请码:</span>
                  <div className="invite-code-container">
                    <div className="invite-code">{inviteCode}</div>
                    <div className="invite-code-actions">
                      <button className="invite-code-button refresh" onClick={handleRefreshInviteCode}>
                        <span className="refresh-icon">↻</span>
                      </button>
                      {/* <button className="invite-code-button copy" onClick={handleCopyInviteCode}>
                        <span className="copy-icon">📋</span>
                      </button> */}
                    </div>
                    {copySuccess && <span className="copy-success">已复制!</span>}
                  </div>
                </div>
              </div>
              <div className="group-buttons">
                <button className="edit-button" onClick={handleOpenEditModal}>
                  编辑资料
                </button>
                {localStorage.getItem('role') === 'admin' && (
                  <button className="ban-button" onClick={handleBatchBanUsers}>
                    封禁用户
                  </button>
                )}
              </div>
            </div>
          </div>

          <div className="profile-content">
            <div className="profile-tabs">
              <button
                className={`tab-button ${activeTab === "downloads" ? "active" : ""}`}
                onClick={() => setActiveTab("downloads")}
              >
                下载视频
              </button>
              <button
                className={`tab-button ${activeTab === "uploads" ? "active" : ""}`}
                onClick={() => setActiveTab("uploads")}
              >
                上传视频
              </button>
            </div>

            <div className="tab-content">
              {activeTab === "downloads" && (
                <div className="downloads-tab">
                  {isLoading ? (
                    <div className="loading-state">加载中...</div>
                  ) : error ? (
                    <div className="error-state">
                      <p>出错了: {error}</p>
                      <button onClick={() => fetchDownloadRecords(currentPage)} className="retry-button">
                        重试
                      </button>
                    </div>
                  ) : downloads.length > 0 ? (
                    <>
                      <p className="collection-count">您共有 {totalCount} 个下载记录</p>

                      <div className="downloads-table">
                        <table>
                          <thead>
                            <tr>
                              <th>名称</th>
                              <th>下载时间</th>
                              <th>大小</th>
                            </tr>
                          </thead>
                          <tbody>
                            {downloads.map((download) => (
                              <tr key={download.downloadId}>
                                <td className="download-title-cell">
                                  <div className="download-title-with-image">
                                    <span>{download.torrentTitle}</span>
                                  </div>
                                </td>
                                <td>
                                  {new Date(download.downloadTime).toLocaleString()}
                                </td>
                                <td>{formatSize(download.downloadSize)}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>

                      <div className="pagination">{renderPagination()}</div>
                    </>
                  ) : (
                    <p>您还没有下载任何视频</p>
                  )}
                </div>
              )}

              {activeTab === "uploads" && (
                <div className="uploads-tab">
                  {isLoading ? (
                    <div className="loading-state">加载中...</div>
                  ) : error ? (
                    <div className="error-state">
                      <p>出错了: {error}</p>
                      <button onClick={fetchUserTorrents} className="retry-button">
                        重试
                      </button>
                    </div>
                  ) : torrents.length > 0 ? (
                    <>
                      <p className="collection-count">您共上传了 {torrents.length} 个种子</p>
                      <div className="downloads-table">
                        <table>
                          <thead>
                            <tr>
                              <th>名称</th>
                              <th>上传时间</th>
                              <th>类别</th>
                              <th>操作</th>
                            </tr>
                          </thead>
                          <tbody>
                            {torrents.map((torrent) => (
                              <tr key={torrent.torrentId}>
                                <td className="download-title-cell">
                                  <div className="download-title-with-image">
                                    <span>{torrent.title}</span>
                                  </div>
                                </td>
                                <td>
                                  {new Date(torrent.uploadTime).toLocaleString()}
                                </td>
                                <td>{torrent.category}</td>
                                <td>
                                  <button 
                                    className="action-button delete"
                                    onClick={() => handleDeleteUploadRecord(torrent.torrentId)}
                                  >删除</button>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </>
                  ) : (
                    <p>您还没有上传任何种子</p>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {isEditModalOpen && (
        <div className="modal-overlay">
          <div className="modal-content">
            <h2>编辑个人资料</h2>
            <form onSubmit={handleEditSubmit}>
              <div className="form-group">
                <label>用户名</label>
                <input
                  type="text"
                  value={editForm.nickname}
                  onChange={(e) => setEditForm({ ...editForm, nickname: e.target.value })}
                  required
                  maxLength="20"
                />
              </div>

              <div className="form-group">
                <label>性别</label>
                <select value={editForm.gender} onChange={(e) => setEditForm({ ...editForm, gender: e.target.value })}>
                  <option value="">请选择</option>
                  <option value="male">男</option>
                  <option value="female">女</option>
                </select>
              </div>

              <div className="form-group">
                <label>个性签名</label>
                <textarea
                  value={editForm.bio}
                  onChange={(e) => setEditForm({ ...editForm, bio: e.target.value })}
                  rows="3"
                  maxLength="200"
                  placeholder="介绍一下自己吧..."
                />
              </div>

              <div className="modal-buttons">
                <button type="submit" className="save-button" disabled={isLoading}>
                  {isLoading ? "保存中..." : "保存"}
                </button>
                <button type="button" className="cancel-button" onClick={handleModalClose} disabled={isLoading}>
                  取消
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}

export default ProfilePage
